var start=null,countdown=require('../public/javascripts/countdown'),sdc = require('sdc-clients'),dc_config=require('../config/dc')['poc'],vmapi = new sdc.VMAPI(dc_config.vmapi),opt={brand: 'joyent'},params=require('./config').params,readline = require('readline'),rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
})

repl()
function repl(){
	if(params.length){
		var param=params.pop()
		rl.question('请输入'+param.id+'('+param.flag+'):\n'+(param.ex?param.ex+'\n':''), function(answer) {
			opt[param.id]=answer||param.default
			repl()
		})
	}else{
		opt.networks=[{primary: true, uuid: opt.networks}]
		console.log('配置：',opt,'\n')
		rl.question('确定要继续吗？回车继续，任意键+回车退出！！！\n', function(answer) {
			if(answer)process.exit(1)
			else{
				rl.close()
				start=new Date()
				if(opt.serialize=='false')for(var i=0;i<opt.vm_num;i++)create(i)
				else serializeCreate()
			}
		})
	}
}
function create(i){
	var begin=new Date()
	vmapi.createVm(opt,function (err, obj) {//开始顺序与结束顺序可能不同
		var end=new Date()
		if(err)err(err)
		else{
			console.log('创建成功：',obj.vm_uuid,'用时：',countdown(end,begin,countdown.ALL).toString(),'启动中...',i,begin.getTime(),end.getTime())
			//cometState(obj.vm_uuid,'',0,begin)
		}
	})
}
function serializeCreate(){
	if(opt.vm_num){
		console.log('\n序列化创建第'+opt.vm_num+'台主机')
		var begin=new Date()
		vmapi.createVm(opt,function(err, obj) {
			var end=new Date()
			--opt.vm_num
			if(err){
				err(err)
				serializeCreate()
			}else{
				console.log('第'+(opt.vm_num+1)+'台主机已创建，uuid：'+obj.vm_uuid,
					'，api响应时间：',countdown(end,begin,countdown.ALL).toString(),
					'('+begin.getTime()+'~'+end.getTime()+')')
				cometState(obj.vm_uuid,'',0,begin)
			}
		})
	}else{
		console.log('\n所有主机创建完毕，总耗时：',countdown(new Date(),start,countdown.ALL).toString())
		process.exit(1)
	}
}
function err(err){
	if(err.body&&err.body.errors)
		for(var e in err.body.errors)
			console.log(err.body.errors[e])
	else console.log(err)
}
function cometState(vm_uuid,state,i,begin){
	vmapi.getVm({uuid:vm_uuid},function(err, vm){
		if (err)err(err)
		else if(vm.state){
			if(state!=vm.state){
				state=vm.state
				console.log(state)
			}
			if(state!='running'&&i<10000)cometState(vm_uuid,state,++i,begin)
			else{
				var end=new Date()
				if(state!='running')console.log('Time out！')
				console.log('轮询'+i+'次,耗时:',countdown(end,begin,countdown.ALL).toString(),'IP:',vm.nics?vm.nics[0].ip:'null')
				serializeCreate()
			}
		}
	})
}